<template>
  <el-pagination
    v-show="total > 0"
    :ref="changeRef"
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :background="true"
    :page-sizes="[10, 20, 30, 50, 100]"
    :pager-count="pagerCount"
    :total="total"
    :small="isSmall"
    layout="total, sizes, prev, pager, next, jumper"
    v-bind="$attrs"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <slot></slot>
  </el-pagination>
</template>

<script lang="ts" setup>
import { useAppStoreWithOut } from '@/store/modules/app'
import type { ZPaginationProps } from '../types'

defineOptions({ name: 'ZPagination', inheritAttrs: false })

const props = withDefaults(defineProps<ZPaginationProps>(), {
  // 总条目数
  total: 200,
  // 设置最大页码按钮数。 页码按钮的数量，当总页数超过该值时会折叠，移动端页码按钮的数量端默认值 5
  pagerCount: document.body.clientWidth < 992 ? 5 : 7
})

const vm = getCurrentInstance()
// 此处解决了当全局size为small的时候分页组件样式太大的问题
const appStore = useAppStoreWithOut()
const layoutCurrentSize = computed(() => appStore.currentSize)
const isSmall = ref<boolean>(layoutCurrentSize.value === 'small')

watchEffect(() => {
  isSmall.value = layoutCurrentSize.value === 'small'
})

const emit = defineEmits(['pagination'])

const currentPage = defineModel('pageNo', {
  type: Number,
  default: 1
})

const pageSize = defineModel('limit', {
  type: Number,
  default: 20
})

const handleSizeChange = (val: number) => {
  // 如果修改后超过最大页面，强制跳转到第 1 页
  if (currentPage.value * val > props.total) {
    currentPage.value = 1
  }
  // 触发 pagination 事件，重新加载列表
  emit('pagination', { page: currentPage.value, limit: val })
}

const handleCurrentChange = (val: number) => {
  // 触发 pagination 事件，重新加载列表
  emit('pagination', { page: val, limit: pageSize.value })
}

const changeRef = (IconInstance: Record<string, any> | null) => {
  if (vm) {
    vm.exposeProxy = vm.exposed = Object.assign(
      IconInstance || {},
      {} // 这里写暴露的方法
    )
  }
}

defineExpose(vm?.exposeProxy || {})
</script>
